package com.xdy.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.xdy.reggie.common.R;
import com.xdy.reggie.dto.DishDto;
import com.xdy.reggie.entity.Dish;
import com.xdy.reggie.entity.DishFlavor;
import com.xdy.reggie.service.DishFlavorService;
import com.xdy.reggie.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
@Api(tags = "菜品接口控制器")
public class DishController {

    @Resource
    private DishService dishService;

    @Resource
    private DishFlavorService dishFlavorService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping
    @ApiOperation("添加菜品接口")
    public R<String> save(@ApiParam("保存的菜品信息以及菜品口味信息") @RequestBody DishDto dishDto){
        log.info("添加菜品 ===> {}",dishDto);
        dishService.saveWithFlavor(dishDto);
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("添加成功！");
    }

    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, String name){
        Page<Dish> dishPage = new Page<>(page,pageSize);
        Page<DishDto> pageInfo = dishService.getWithCategoryName(dishPage,name);
        return R.success(pageInfo);
    }

    @GetMapping("/{id}")
    public R<DishDto> getByDishId(@PathVariable Long id){
        DishDto dishDto = dishService.getWithFlavorByDishId(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> updateWithFlavor(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("修改成功！");
    }

    /**
     * 停售或者起售
     * @return
     */
    @PostMapping("/status/{state}")
    public R<String> stopOrStartSelling(@PathVariable Integer state,@RequestParam List<Long> ids){
        log.info("修改的状态 ===> {}",state);
        log.info("菜品ID ===> {}",ids);
        List<String> keys = new ArrayList<>();
        List<Dish> dishList = ids.stream().map(item -> {
            Dish dish = dishService.getById(item);
            dish.setStatus(state);
            keys.add("dish_"+dish.getCategoryId().toString()+"_1");
            return dish;
        }).collect(Collectors.toList());
        dishService.updateBatchById(dishList);
        redisTemplate.delete(keys);
        return R.success("成功！");
    }

    /**
     * 删除或批量删除,因为删除之前需要先停售，停售会同步缓存数据，所以删除不需要处理
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(@RequestParam List<Long> ids){
        dishService.removeWithDishFlavor(ids);
        return R.success("删除成功！");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(DishDto dishDto){
        log.info("菜品分类id ===> {}",dishDto.getCategoryId());
        List<DishDto> dishDtos = null;

        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        //从Redis缓存中获取菜品信息
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null){
            //缓存命中返回数据
            return R.success(dishDtos);
        }
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,dishDto.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.eq(Dish::getIsDeleted,0);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(queryWrapper);
        dishDtos = dishList.stream().map(item -> {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item,dto);
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getIsDeleted,0);
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dto.setFlavors(dishFlavors);
            return dto;
        }).collect(Collectors.toList());
        //未命中时查询出的菜品信息，添加到缓存,60分钟内有效
        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }
}
